<template>
	<div class="fenxiangdianpu">
    <div v-if="!store_poster" style="font-size: 12px;">
      努力生成中...请稍等
    </div>
    <img :src="store_poster">
    <!-- <canvas id="canvas"></canvas> -->
    <div v-if="store_poster && !weixin" class="flexcc" style="background: rgb(0, 90, 255); margin: 0.6rem auto 0; width: 4.6rem; height: 0.9rem; box-shadow: 0px 0.1rem 0.2rem 0px rgba(0, 90, 255, 0.1); border-radius: 0.45rem; font-size: 0.31rem; color: rgb(255, 255, 255);" @click="xiazai">保存</div>

    <div v-if="store_poster && weixin" class="flexcc" style="margin: 0.6rem auto 0; width: 4.6rem; height: 0.9rem; border-radius: 0.45rem; font-size: 0.31rem; color: #666; ">长按图片保存</div>
	</div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import * as qiniu from 'qiniu-js'


  if(window.screen.width < 1080){
    var h = document.documentElement.clientWidth / 7.5 + 'px';
    document.documentElement.style.fontSize = h;
  }
	export default {
		name: 'query',

		data() {
			return {
        obj2:{ },

        canvas:"",
        store_poster:"",
        weixin:false

			}
		},
		created() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/micromessenger/i) == 'micromessenger') {
           this.weixin = true
      }
		},
		mounted() {

      let copyurl = location.origin + '/h5/index?shop_id=' + window.btoa(JSON.parse(localStorage.getItem('user')).id)

      let erweima = document.createElement('div')
      const qrCode = new QRCode(erweima, {
        text: copyurl, // 要生成二维码的文本
        width: 400,                  // 二维码宽度
        height: 400,                 // 二维码高度
        colorDark : '#000000',       // 二维码颜色
        colorLight : '#ffffff',
        padding:10,
        correctLevel : QRCode.CorrectLevel.H     // 二维码容错率
      });





              let url = '/agent/poster/info'
              // if(this.$route.query.shop_id){
              //   url = '/agent/mstore/poster/info?shop_id=' + window.atob(this.$route.query.shop_id)
              // }
              // if(this.$route.query.shops_id){
              //   url = '/agent/flow/poster/info?id=' + this.$route.query.shops_id
              // }


              // alert(erweima.getElementsByTagName('img'))
              // alert(JSON.stringify(erweima.getElementsByTagName('img')))
              // alert(JSON.stringify(erweima.getElementsByTagName('img')[0]).src)
              // this.test = erweima.getElementsByTagName('img')[0].src
              // console.log(this.test)
              axios.get(url).then((response)=>{
              	if (response.data.msg.code == 0) {
                  this.obj2 = {
                    store_template:response.data.data.store_template,
                    store_img:response.data.data.store_img,
                    image2:response.data.data.left_pic,
                    store_color:response.data.data.store_color,
                    image3:response.data.data.left_pic,//头像
                    store_des:response.data.data.store_des,
                    image4:erweima.getElementsByTagName('canvas')[0].toDataURL("image/jpg"),//二维码
                    store_name:response.data.data.store_name
                  }
                  this.haibao()
              	}else {
              	}
              })






		},
		methods: {
      xiazai:function(){
        this.baocun()
      },
      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },
      //单个图片上传
      uploadok: function(file,t) {
        let name = this.getRandomChar() + '.' + 'png'
        var that = this
        axios.post(`/api/qiniu/uploadtoken`,{name:name})
          .then(response => {
            if(response.data.msg.code == 0){
              const observer = {
                next(res){},
                error(err){},
                complete(res){
                  window.location.href = 'https://gperson.gantanhaokeji.top/'+ res.key + '?attname='
                  // that.all.store_poster = 'https://gperson.gantanhaokeji.top/'+ res.key
                }
              }
              const observable = qiniu.upload(file, name, response.data.data.token, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始
            }else{
              this.$message.error(response.data.msg.info);
            }
          });
      },
      dataURLtoFile:function(dataurl, filename) {
      	let arr = dataurl.split(',');
      	let mime = arr[0].match(/:(.*?);/)[1];
      	let bstr = atob(arr[1]);
      	let n = bstr.length;
      	let u8arr = new Uint8Array(n);
      	while (n--) {
      		u8arr[n] = bstr.charCodeAt(n);
      	}
      	return new File([u8arr], filename, {
      		type: mime
      	});
      },
      baocun:function(){
        let file = this.dataURLtoFile(this.canvas.toDataURL('image/jpg'),'haibao')
        this.uploadok(file)
      },
      haibao:function(){
        var that = this


            if(this.obj2.store_template == 1){
              // var canvas = document.getElementById('canvas')
              var canvas = document.createElement('canvas');

              this.canvas = canvas

              canvas.width = 340 * 2
              canvas.height = 600 * 2

              var ctx = canvas.getContext('2d');
              var img = new Image();
              let p = new Promise((res,rej)=>{
              	img.src = this.obj2.store_img
              	img.setAttribute("crossOrigin",'Anonymous')
              	img.onload = function() {
              		let img_w = 340 * 2
              		let bili = 340 * 2 / img.width
              		let img_h = parseInt(img.height * bili)
              		ctx.drawImage(img,0,0,img_w,img_h);
              		res('ok')
              	}
              })
              p.then(()=>{
                let p2 = new Promise((res2,rej2)=>{
                  var img3 = new Image();
                  img3.src = this.obj2.image3
                  img3.setAttribute("crossOrigin",'Anonymous')
                  img3.onload = function() {
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(340, 389, 78, 0, Math.PI * 2, false);
                    ctx.clip();
                    ctx.drawImage(img3,262,311,156,156);
                    ctx.restore();
                    res2('ok')
                  }
                })
                p2.then(()=>{
                  ctx.textBaseline="middle";
                  ctx.fillStyle = this.obj2.store_color;
                  ctx.fontWeight = 'bold'
                  ctx.lineHeight = '42px';
                  ctx.font = "36px '微软雅黑'";
                  ctx.textAlign="center";
                  ctx.fillText(this.obj2.store_name, 170 * 2,503)


                  ctx.textBaseline="middle";
                  ctx.fillStyle = this.obj2.store_color;
                  ctx.lineHeight = '76px';
                  ctx.font = "32px '微软雅黑'";
                  ctx.textAlign="center";
                  let hang1 = this.obj2.store_des.substring(0,12) || ''
                  let hang2 = this.obj2.store_des.substring(12,26) || ''
                  ctx.fillText(hang1, 340,568)
                  ctx.fillText(hang2, 340,610)


                  var img4 = new Image();
                  img4.src = this.obj2.image4
                  img4.setAttribute("crossOrigin",'Anonymous')
                  img4.onload = function() {

                    ctx.fillStyle = "#ffffff";
                    ctx.fillRect(225, 673, 254, 254);

                    ctx.drawImage(img4,235,683,234,234);
                    that.store_poster = canvas.toDataURL('image/jpg')
                  }
                })
              })
            }
            if(this.obj2.store_template == 2){
              // var canvas = document.getElementById('canvas')
              var canvas = document.createElement('canvas');
              this.canvas = canvas

              canvas.width = 340 * 2
              canvas.height = 600 * 2
              var ctx = canvas.getContext('2d');
              var img = new Image();
              let p = new Promise((res,rej)=>{
              	img.src = this.obj2.store_img
              	img.setAttribute("crossOrigin",'Anonymous')
              	img.onload = function() {
              		let img_w = 340 * 2
              		let bili = 340 * 2 / img.width
              		let img_h = parseInt(img.height * bili)
              		ctx.drawImage(img,0,0,img_w,img_h);
              		res('ok')
              	}
              })
              p.then(()=>{
                let p2 = new Promise((res2,rej2)=>{
                  var img3 = new Image();
                  img3.src = this.obj2.image3
                  console.log(img3)
                  img3.setAttribute("crossOrigin",'Anonymous')
                  img3.onload = function() {
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(175.5, 955.5, 57.5, 0, Math.PI * 2, false);
                    ctx.clip();
                    ctx.drawImage(img3,118,898,115,115);
                    ctx.restore();
                    res2('ok')
                  }
                })
                p2.then(()=>{
                  ctx.textBaseline="middle";
                  ctx.fillStyle = this.obj2.store_color;
                  ctx.fontWeight = 'bold'
                  ctx.lineHeight = '35px';
                  ctx.font = "30px '微软雅黑'";
                  ctx.textAlign="center";
                  ctx.fillText(this.obj2.store_name, 175,1050)

                  ctx.textBaseline ="middle";
                  ctx.fillStyle = this.obj2.store_color;
                  ctx.lineHeight = '40px';
                  ctx.font = "22px '微软雅黑'";
                  ctx.textAlign = "center";
                  let hang1 = this.obj2.store_des.substring(0,12) || ''
                  let hang2 = this.obj2.store_des.substring(12,26) || ''
                  ctx.fillText(hang1, 175,1090)
                  ctx.fillText(hang2, 175,1130)

                  var img4 = new Image();
                  img4.src = this.obj2.image4
                  img4.setAttribute("crossOrigin",'Anonymous')
                  img4.onload = function() {
                    ctx.fillStyle = "#ffffff";
                    ctx.fillRect(405, 895, 232, 232);

                    ctx.drawImage(img4,415,905,212,212);
                    that.store_poster = canvas.toDataURL('image/jpg')
                  }
                })
              })
            }


      },
		}
	}
</script>


<style scoped lang="less">

</style>
